package com.aliyun.heiyu.powermaster.server.rbac.service;

import com.aliyun.heiyu.common.util.DateUtil;
import com.aliyun.heiyu.common.util.LogUtils;
import com.aliyun.heiyu.common.util.StringUtil;
import com.aliyun.heiyu.powermaster.proto.AuditManagementQueryReply;
import com.aliyun.heiyu.powermaster.proto.AuditManagementReply;
import com.aliyun.heiyu.powermaster.proto.AuditManagementRequest;
import com.aliyun.heiyu.powermaster.server.Error;
import com.aliyun.heiyu.powermaster.server.rbac.dao.SysAuditManagementsDao;
import com.aliyun.heiyu.powermaster.server.rbac.dao.impl.SysAuditManagementsDaoImpl;
import com.aliyun.heiyu.powermaster.server.rbac.object.entity.SysAuditManagements;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;

public class SysAuditManagementsServiceImpl implements SysAuditManagementsService {

    private Logger logger = Logger.getLogger(getClass().getName());

    private final String timePatten = "yyyy-MM-dd HH:mm:ss";

    private final SysAuditManagementsDao auditManagementsDao;

    public SysAuditManagementsServiceImpl(){
        auditManagementsDao = new SysAuditManagementsDaoImpl();
    }

    @Override
    public AuditManagementReply saveAuditManagement(AuditManagementRequest auditManagement) {
        AuditManagementReply.Builder builder = AuditManagementReply.newBuilder();
        String msg = validateAuditManagementRequest(auditManagement);
        builder.setErrCode(896);
        if (msg == null){
            SysAuditManagements userAuditManagement = auditManagementsDao.getAuditManagementByUserName(auditManagement.getUserName());
            if (userAuditManagement != null){
                msg = "该用户已存在该策略";

            }else {
                SysAuditManagements sysAuditManagement = new SysAuditManagements();
                msg = getSysAuditManagements(auditManagement,sysAuditManagement);
                if (msg == null){
                    auditManagementsDao.saveAuditManagement(sysAuditManagement);
                    msg = Error.SUCCESS.getMessage();
                    builder.setErrCode(Error.SUCCESS.getCode());
                }
            }

        }
        return builder.setErrMsg(msg)
            .build();
    }

    private String validateAuditManagementRequest(AuditManagementRequest auditManagement) {

        if (StringUtil.isEmpty(auditManagement.getStartTime())){
            return "开始时间不能为空";
        }
        if (StringUtil.isEmpty(auditManagement.getEndTime())){
            return "结束时间不能为空";
        }

        if (StringUtil.isEmpty(auditManagement.getUserName())){
            return "用户不能为空";
        }

        if (!StringUtil.isEmpty(auditManagement.getDescription()) &&
            auditManagement.getDescription().length() > 500){
            return "描述不合法，描述长度不能超过500";
        }

        return null;
    }

    private String getSysAuditManagements(AuditManagementRequest auditManagement,SysAuditManagements sysAuditManagements) {

        sysAuditManagements.setBusinessModule(auditManagement.getBusinessModule());
        sysAuditManagements.setDescription(auditManagement.getDescription());
        sysAuditManagements.setEventType(auditManagement.getEventType());
        sysAuditManagements.setOperationType(auditManagement.getOperationType());
        sysAuditManagements.setUserName(auditManagement.getUserName());
        DateFormat dateFormat = new SimpleDateFormat(timePatten);

        if (!StringUtil.isEmpty(auditManagement.getStartTime()) ){
            try {
                sysAuditManagements.setStartTime(dateFormat.parse(auditManagement.getStartTime()));
            }catch (ParseException e){
                return "开始时间格式不正常";
            }
        }else {
            return "开始时间不能为空";
        }

        if (!StringUtil.isEmpty(auditManagement.getEndTime()) ){
            try {
                sysAuditManagements.setEndTime(dateFormat.parse(auditManagement.getEndTime()));
            }catch (ParseException e){
                return "结束时间格式不正常";
            }
        }else {
            return "结束时间不能为空";
        }
        if (sysAuditManagements.getEndTime().before(sysAuditManagements.getStartTime())){
            return "开始时间必须在结束时间之前";
        }

        return null;
    }

    @Override
    public AuditManagementReply updateAuditManagement(AuditManagementRequest auditManagement) {
        String msg = validateAuditManagementRequest(auditManagement);
        int code = 211;
        if (msg == null){
            SysAuditManagements sysAuditManagements = new SysAuditManagements();
            msg = getSysAuditManagements(auditManagement,sysAuditManagements);
            if (msg == null){
                int id = auditManagement.getId();
                if (id <= 0){
                    msg = "数据不能为空";
                }else {
                    SysAuditManagements audit = auditManagementsDao.getAuditManagementById(id);
                    if (audit == null){
                        msg = "数据不存在";
                    }else {
                        //更新
                        sysAuditManagements.setId(id);
                        boolean b = auditManagementsDao.updateAuditManagement(sysAuditManagements);
                        if (!b){
                            logger.warning("更新策略失败，策略主键："+ id);
                        }
                        code = Error.SUCCESS.getCode();
                        msg = Error.SUCCESS.getMessage();
                    }
                }
            }


        }

        return AuditManagementReply.newBuilder()
            .setErrCode(code)
            .setErrMsg(msg)
            .build();
    }

    @Override
    public AuditManagementReply deleteAuditManagement(Integer auditManagementId) {
        if (auditManagementId <= 0){
            return AuditManagementReply.newBuilder()
                .setErrCode(121)
                .setErrMsg("数据不能为空")
                .build();
        }
        SysAuditManagements audit = auditManagementsDao.getAuditManagementById(auditManagementId);
        if (audit == null){
            return AuditManagementReply.newBuilder()
                .setErrCode(121)
                .setErrMsg("数据不存在")
                .build();
        }

        auditManagementsDao.deleteAuditManagement(auditManagementId);

        return AuditManagementReply.newBuilder()
            .setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage())
            .build();
    }

    @Override
    public AuditManagementQueryReply getAuditManagements(AuditManagementRequest auditManagementRequest) {
        AuditManagementQueryReply.Builder builder = AuditManagementQueryReply.newBuilder()
            .setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage());
        int page = auditManagementRequest.getPage();
        int pageSize = auditManagementRequest.getPageSize();
        int startNum = 0;
        int endNum = pageSize;
        if (page >= 0){
            startNum = (page - 1) * pageSize;
        }
        Integer count = auditManagementsDao.getAuditManagementsCount(auditManagementRequest.getBusinessModule());

        if (count != null && count > 0){
            List<SysAuditManagements> auditManagements = auditManagementsDao.getAuditManagements(startNum, endNum, auditManagementRequest.getBusinessModule());
            for (SysAuditManagements auditManagement : auditManagements) {
                AuditManagementQueryReply.Data data = getQueryData(auditManagement);
                builder.addData(data);
            }
        }
        builder.setTotal(count);
        builder.setCurrentPage(page);
        return builder.build();
    }

    @Override
    public AuditManagementQueryReply getAuditManagementById(Integer auditManagementId) {
        if (auditManagementId <= 0){
            return AuditManagementQueryReply.newBuilder()
                .setErrCode(Error.SUCCESS.getCode())
                .setErrMsg("数据不能为空")
                .build();
        }
        SysAuditManagements audit = auditManagementsDao.getAuditManagementById(auditManagementId);
        if (audit == null){
            return AuditManagementQueryReply.newBuilder()
                .setErrCode(Error.SUCCESS.getCode())
                .setErrMsg("数据不存在")
                .build();
        }
        AuditManagementQueryReply.Data data = getQueryData(audit);
        return AuditManagementQueryReply.newBuilder()
            .setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage())
            .addData(data)
            .build();
    }

    private AuditManagementQueryReply.Data getQueryData(SysAuditManagements audit) {

        AuditManagementQueryReply.Data.Builder builder = AuditManagementQueryReply.Data.newBuilder();


        if (audit.getStartTime() != null){
            builder.setStartTime(DateUtil.dateToString(audit.getStartTime()));

        }
        if (audit.getEndTime() != null){
            builder.setEndTime(DateUtil.dateToString(audit.getEndTime()));
        }

        if (!StringUtil.isEmpty(audit.getBusinessModule())){
            builder
                .setBusinessModule(audit.getBusinessModule());
        }
        if (!StringUtil.isEmpty(audit.getDescription())){
            builder
                .setDescription(audit.getDescription());
        }

        if (!StringUtil.isEmpty(audit.getEventType())){
            builder
                .setEventType(audit.getEventType());
        }else {
            builder
                .setEventType("");
        }

        if (!StringUtil.isEmpty(audit.getOperationType())){
            builder
                .setOperationType(audit.getOperationType());
        }else {
            builder
                .setOperationType("");
        }

        if (!StringUtil.isEmpty(audit.getUserName())){
            builder
                .setUserName(audit.getUserName());
        }

        return builder
            .setId(audit.getId())
            .build();
    }
}
